import {
	HTTP_REQUEST_URL,
	HEADER,
	TOKENNAME
} from '@/config/config.js';

/**
 * 发送请求
 */
function baseRequest(url, method, data) {
	let baseUrl = HTTP_REQUEST_URL,
		header = HEADER;
	let token = uni.getStorageSync('token')
	if (token) header[TOKENNAME] = token;

	return new Promise((reslove, reject) => {
		uni.request({
			url: baseUrl + url,
			method: method || 'GET',
			header: header,
			data: data || {},
			success: (res) => {
				if (res.statusCode == 200) {
					if(res.data.code == 1) {
						reslove(res.data);
					} else {
						uni.showToast({
							title: res.data.msg,
							icon: 'none'
						})
						reject(res.data.msg);
					}
				} else if (res.statusCode == 401) {
					uni.showToast({
						title: res.data.msg,
						icon: 'none'
					})
					reject(res.data.msg);
				} else if (res.statusCode == 500) {
					uni.showToast({
						title: '网络API接口异常',
						icon: 'none'
					})
					reject(res.data.msg || `系统错误`);
				} else {
					reject(res.data.msg || `系统错误`);
				}
			},
			fail: (msg) => {
				reject(`请求失败`);
			}
		})
	});
}

const request = {};

['options', 'get', 'post', 'put', 'head', 'delete', 'trace', 'connect'].forEach((method) => {
	request[method] = (api, data, opt) => baseRequest(api, method, data, opt || {})
});

export default request;